package com.qiezikaka.kaka.utils;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;

import androidx.annotation.ColorInt;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class QRCodeUtil {

    private static final int QR_CODE_SIZE = 200;

    /**
     * 生成带logo的二维码
     *
     * @param content  二维码内容
     * @param logoBitmap logo图片的Bitmap对象
     * @return 带logo的二维码的Bitmap对象
     */
    public static Bitmap generateQRCodeWithLogo(String content, Bitmap logoBitmap) {
        Bitmap qrBitmap = null;

        try {
            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            // 生成二维码
            QRCodeWriter writer = new QRCodeWriter();
            BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hints);

            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            qrBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    qrBitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
                }
            }

            // 添加logo
            if (logoBitmap != null) {
                qrBitmap = addLogoToQRCode(qrBitmap, logoBitmap);
            }

        } catch (WriterException e) {
            e.printStackTrace();
        }

        return qrBitmap;
    }

    private static Bitmap addLogoToQRCode(Bitmap qrBitmap, Bitmap logoBitmap) {
        if (qrBitmap == null) {
            return null;
        }

        int qrBitmapWidth = qrBitmap.getWidth();
        int qrBitmapHeight = qrBitmap.getHeight();
        int logoBitmapWidth = logoBitmap.getWidth();
        int logoBitmapHeight = logoBitmap.getHeight();

        float scaleFactor = qrBitmapWidth * 1.0f / 5 / logoBitmapWidth;
        Bitmap scaledLogoBitmap = Bitmap.createScaledBitmap(logoBitmap, (int) (logoBitmapWidth * scaleFactor),
                (int) (logoBitmapHeight * scaleFactor), true);

        Canvas canvas = new Canvas(qrBitmap);
        canvas.drawBitmap(scaledLogoBitmap, qrBitmapWidth / 2 - scaledLogoBitmap.getWidth() / 2,
                qrBitmapHeight / 2 - scaledLogoBitmap.getHeight() / 2, new Paint());
        canvas.save();
        canvas.restore();

        return qrBitmap;
    }
}